package com.yaozheng.vocationaltraining.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EBean;

import com.yaozheng.vocationaltraining.iview.BaseView;
import com.yaozheng.vocationaltraining.iview.IBaseView;
import com.yaozheng.vocationaltraining.iview.ITokenBaseView;
import com.yaozheng.vocationaltraining.iview.ITrainingBulletinView;
import com.yaozheng.vocationaltraining.service.NewsListService;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.http.okhttp.OkHttpClientManager;

/**
 * 新闻服务
 * 
 * @author Administrator
 * 
 */
@EBean
public class NewsListServiceImpl implements NewsListService {
	ITrainingBulletinView iTrainingBulletinView;

	@Override
	public void init(ITrainingBulletinView iTrainingBulletinView) {
		this.iTrainingBulletinView = iTrainingBulletinView;
	}

	@Background
	@Override
	public void newsList(int cat, int offset) {
		try {
			OkHttpClientManager.getInstance().get(
					Constants.ROOTURL + "/news/list?cat=" + cat + "&offset="
							+ offset, iTrainingBulletinView.getToken(),
					iTrainingBulletinView);
		} catch (Exception e) {
			ErrorUtils.outErrorLog(e);
			iTrainingBulletinView
					.responseError(ErrorUtils.SERVER_CONNECTION_ERROR);

		}
	}

	@Background
	@Override
	public void signUp(int id, boolean applied) {
		String executeMethod;
		if (applied) {
			executeMethod = "/training/cancel";
		} else {
			executeMethod = "/training/apply";
		}
		try {
			Map<String, String> para = new HashMap<String, String>();
			para.put("id", String.valueOf(id));
			OkHttpClientManager.getInstance().post(
					Constants.ROOTURL + executeMethod,
					iTrainingBulletinView.getToken(), para,
					new OkHttpClientManager.IBaseViewCallback(new BaseView(iTrainingBulletinView) {

						@Override
						public void responseSuccess(JSONObject jsonObject) {
							iTrainingBulletinView.signUpSuccess(jsonObject);
						}

						@Override
						public void responseError(String error) {
							iTrainingBulletinView.signUpError(error);
						}

					}));
		} catch (Exception e) {
			ErrorUtils.outErrorLog(e);
			if (iTrainingBulletinView.isResponseResult()) {
				iTrainingBulletinView
						.signUpError(ErrorUtils.SERVER_CONNECTION_ERROR);
			}

		}
	}
}
